<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./utils/reset.css" />
    <title>12利用三角形绘制圆形</title>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script type="shader-source" id="vertexShader">
      precision mediump float;
      attribute vec2 canvas_Size;
      attribute vec2 triangle_Position;
      attribute vec4 triangle_Color;
      varying vec4 v_Color;

      void main(){
          vec2 position = (triangle_Position / canvas_Size) * 2.0 - 1.0;
          position = position * vec2(1.0, -1.0);
          gl_Position = vec4(position, 0.0, 1.0);
          v_Color = triangle_Color;
      }
    </script>
    <script type="shader-source" id="fragmentShader">
      precision mediump float;
      varying vec4 v_Color;

      void main(){
          vec4 color = v_Color / vec4(255,255,255,1);
          gl_FragColor = color;
      }
    </script>
    <script src="./utils/webgl-helper.js"></script>
    <script>
      function createCircleVertex(x, y, radius, n) {
        const positions = [x, y, 255, 255, 0, 1];
        for (let i = 0; i <= n; i++) {
          const angle = (i * Math.PI * 2) / n;
          positions.push(
            x + radius * Math.sin(angle),
            y + radius * Math.cos(angle),
            255,
            0,
            0,
            1
          );
        }
        return positions;
      }
      const canvas = getCanvas("#canvas");
      resizeCanvas(canvas);

      const gl = getContext(canvas);

      const program = createSimpleProgramFromScript(
        gl,
        "vertexShader",
        "fragmentShader"
      );
      gl.useProgram(program);

      const canvas_Size = gl.getAttribLocation(program, "canvas_Size");
      gl.vertexAttrib2f(canvas_Size, canvas.width, canvas.height);

      const positions = createCircleVertex(100, 100, 50, 50);

      let triangle_Position = gl.getAttribLocation(
        program,
        "triangle_Position"
      );
      let triangle_Color = gl.getAttribLocation(program, "triangle_Color");

      gl.enableVertexAttribArray(triangle_Position);
      gl.enableVertexAttribArray(triangle_Color);

      const buffer = gl.createBuffer();
      // 绑定缓冲区为当前缓冲
      gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
      // 设置 a_Position 属性从缓冲区读取数据方式
      gl.vertexAttribPointer(triangle_Position, 2, gl.FLOAT, false, 24, 0);
      // 设置 a_Color 属性从缓冲区读取数据方式
      gl.vertexAttribPointer(triangle_Color, 4, gl.FLOAT, false, 24, 8);
      // 向缓冲区传递数据
      gl.bufferData(
        gl.ARRAY_BUFFER,
        new Float32Array(positions),
        gl.STATIC_DRAW
      );

      gl.clearColor(0, 0, 0, 1);
      function render(gl) {
        gl.clear(gl.COLOR_BUFFER_BIT);
        gl.drawArrays(gl.TRIANGLE_FAN, 0, positions.length / 6);
      }
      render(gl);
    </script>
  </body>
</html>
